package com.nebula.controller.management;

import com.alibaba.fastjson.JSON;
import com.nebula.common.Const;
import com.nebula.common.PageResult;
import com.nebula.common.Result;
import com.nebula.controller.BaseController;
import com.nebula.entity.User;
import com.nebula.service.IUserService;
import com.nebula.service.impl.UserServiceImpl;
import com.nebula.util.MD5Util;
import com.nebula.util.UUIDUtil;
import com.nebula.vo.UserVo;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author CcccX
 * @since 2020-08-10 22:52
 */
@WebServlet(urlPatterns = "/manage/user")
public class UserController extends BaseController {
    private final IUserService userService = new UserServiceImpl();

    public String index(HttpServletRequest request, HttpServletResponse response) {
        String navId = request.getParameter("id");
        UserVo user = (UserVo) request.getSession().getAttribute(Const.USER_INFO);

        if (userService.checkNavRole(user.getRoleId(), navId)) {
            return Const.FORWARD + Const.DEFAULT_URL + "website/user-control.jsp";
        } else {
            return Const.FORWARD + "role-error.jsp";
        }
    }

    public String findAllAndPage(HttpServletRequest request, HttpServletResponse response) {
        String size = request.getParameter("rows");
        String page = request.getParameter("page");
        if (StringUtils.isBlank(size)) {
            size = Const.SIZE;
        }
        if (StringUtils.isBlank(page)) {
            page = Const.PAGE;
        }
        PageResult<UserVo> pResult = userService.findAllAndPage(Integer.parseInt(page), Integer.parseInt(size));
        Map<String, Object> map = new HashMap<>(2);
        map.put("total", pResult.getTotalCount());
        map.put("rows", pResult.getList());
        return Const.JSON + JSON.toJSONString(map);
    }

    public String findById(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        IUserService userService = new UserServiceImpl();
        User user = userService.findById(id);
        user.setPassword("");
        switch (user.getGender()) {
            case "男":
                user.setGender("male");
                break;
            case "女":
                user.setGender("female");
                break;
            default:
                user.setGender("secret");
        }
        return Const.JSON + JSON.toJSONString(Result.createBySuccess(user));
    }

    public String save(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        String realName = request.getParameter("realName");
        String gender = request.getParameter("gender");
        gender = getGender(gender);
        String roleId = request.getParameter("roleId");
        User user = new User();
        user.setId(UUIDUtil.get32UUID());
        user.setUsername(username);
        user.setPassword(MD5Util.MD5EncodeUtf8("123456"));
        user.setRealname(realName);
        user.setGender(gender);
        user.setRoleId(Integer.parseInt(roleId));
        Date date = new Date();
        user.setCreatedTime(date);
        user.setUpdatedTime(date);
        int resultCount = userService.save(user);
        if (resultCount == 0) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("新增失败"));
        }

        return Const.JSON + JSON.toJSONString(Result.createBySuccessMessage("新增成功"));
    }

    public String update(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        if (StringUtils.isBlank(id)) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("用户ID不能为空"));
        }
        IUserService userService = new UserServiceImpl();
        String realName = request.getParameter("realName");
        String gender = request.getParameter("gender");
        gender = getGender(gender);
        String roleId = request.getParameter("roleId");
        User user = new User();
        user.setId(id);
        user.setRealname(realName);
        user.setGender(gender);
        user.setRoleId(Integer.parseInt(roleId));
        try {
            userService.update(user);
            return Const.JSON + JSON.toJSONString(Result.createBySuccessMessage("修改成功"));
        } catch (Exception e) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("修改失败"));
        }
    }

    public String delete(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        if (StringUtils.isBlank(id)) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("用户ID不能为空"));
        }

        int resultCount = userService.delete(id);
        if (resultCount > 0) {
            return Const.JSON + JSON.toJSONString(Result.createBySuccessMessage("删除成功"));
        }
        return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("删除失败"));
    }

    private String getGender(String gender) {
        switch (gender) {
            case "male":
                gender = "男";
                break;
            case "female":
                gender = "女";
                break;
            case "secret":
                gender = "保密";
                break;
            default:
                gender = "人妖";
        }
        return gender;
    }
}
